package com.spider.im.sms.service;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.spider.im.common.annotation.RedisLock;
import com.spider.im.common.aspect.BusinessException;
import com.spider.im.common.constant.RedisKey;
import com.spider.im.common.constant.RespCodeEnum;
import com.spider.im.common.utils.EncryptionUtils;
import jakarta.annotation.Resource;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SmsService {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private EncryptionUtils encryptionUtils;

    /**
     * 发送短信验证码
     */
    @RedisLock(keys = {"T(cn.hutool.crypto.digest.DigestUtil).md5Hex(#phoneNumber)"})
    public String sendVerificationCode(String phoneNumber) throws InterruptedException {
        String verificationCode = generateVerificationCode();
        // TODO 发送短信
//        try {
//            // 初始化acsClient,暂不支持region化
//            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
//            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
//            IAcsClient acsClient = new DefaultAcsClient(profile);
//
//            // 组装请求对象-具体描述见控制台-文档部分内容
//            SendSmsRequest request = new SendSmsRequest();
//            // 必填:待发送手机号
//            request.setPhoneNumbers(phoneNumber);
//            // 必填:短信签名-可在短信控制台中找到
//            request.setSignName(signName);
//            // 必填:短信模板-可在短信控制台中找到
//            request.setTemplateCode(templateCode);
//
//            // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//
//            request.setTemplateParam("{\"code\":\"" + verificationCode + "\"}");
//
//            // hint 此处可能会抛出异常，注意catch
//            acsClient.getAcsResponse(request);
        //发送成功后将验证码存放到redis
        String encryptPhone = encryptionUtils.encrypt(phoneNumber);
        String key = RedisKey.SMS_LOGIN_CODE_KEY + DigestUtil.md5Hex(encryptPhone);
        RBucket<String> bucket = redissonClient.getBucket(key);
        // 设置过期时间
        bucket.set(verificationCode, 5, TimeUnit.MINUTES);

//        } catch (ClientException e) {
//            throw new BusinessException(RespCodeEnum.SENT_MSM_ERROR);
//        }
        return verificationCode;
    }

    /**
     * 生成验证码
     */
    private String generateVerificationCode() {
        // 生成6位随机数作为验证码
        int code = (int)(Math.random() * 900000 + 100000);
        return String.valueOf(code);
    }

    /**
     * 验证验证码,手机号码需要是密文
     */
    public boolean verifyCode(String phoneNumber, String verificationCode) {
        String key = RedisKey.SMS_LOGIN_CODE_KEY + DigestUtil.md5Hex(phoneNumber);
        // 从Redis中获取验证码
        RBucket<String> bucket = redissonClient.getBucket(key);
        String code = bucket.get();
        if (code == null) {
            throw new BusinessException(RespCodeEnum.VERIFICATION_CODE_EXPIRED);
        }
        // 比较验证码是否匹配,验证结果
        boolean verify = verificationCode.equals(code);
        //验证过后从redis中删除验证码
        bucket.delete();
        return verify;
    }
}